package com.ghsc.ghxc.jsb.ui.live.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityShareListBinding
import com.ghsc.ghxc.jsb.ui.live.adapter.FriendsListAdapter
import com.ghsc.ghxc.jsb.ui.live.bean.MaterialChildInfoBean
import com.ghsc.ghxc.jsb.ui.live.bean.MaterialInfoBean
import com.ghsc.ghxc.jsb.ui.live.view.LiveBlackList
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareLiveAttachment
import com.ghsc.ghxc.jsb.ui.live.view.cust.CusShareSourceAttachment
import com.ghsc.ghxc.jsb.ui.mall.bean.MaterialBean
import com.ghsc.ghxc.jsb.ui.message.bean.ChatDataResultBean
import com.ghsc.ghxc.jsb.view.NotDataView
import com.google.gson.Gson
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.msg.MessageBuilder
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.uinfo.UserService
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import com.netease.yunxin.kit.conversationkit.ui.bean.ExtDataBean
import com.scwang.smart.refresh.layout.api.RefreshLayout
import java.util.ArrayList

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.live.activity
 * 类名：ShareFriendsListActivity
 * 创建时间：2024/5/11 15:11
 * 创建人 @author： xiaolin
 * 描述 ：Todo...分享好友
 */
class ShareFriendsListActivity : BaseVMActivity<ShareListViewModel, ActivityShareListBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_share_list
    }



    override fun attachVMClass(): Class<ShareListViewModel>? {
        return ShareListViewModel::class.java
    }

    private val mAdapter: FriendsListAdapter by lazy { FriendsListAdapter() }
    var mList = arrayListOf<ChatDataResultBean>()
    private var notDataView: View? = null
    var keyword:String=""
    var bundle : Bundle?=null
    var url :String= ""
    var liveID :String =""
    var userNick :String =""

    var userAvatar :String =""
    var coverUrl :String =""
    var liveTitle :String =""

    var anchorId :String =""
    var signIndex:Int=0
    var mShareBean : MaterialBean?= null
    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        bundle=intent.extras
        signIndex=bundle!!.getInt("signIndex")
        url=bundle!!.getString("url","")
        liveID=bundle!!.getString("liveID","")
        userNick=bundle!!.getString("userNick","")
        userAvatar=bundle!!.getString("userAvatar","")
        coverUrl=bundle!!.getString("coverUrl","")
        liveTitle=bundle!!.getString("liveTitle","")
        anchorId=bundle!!.getString("anchorId","")
        if (signIndex==2)
            mShareBean= bundle!!.getSerializable("bean") as MaterialBean?
        binding.bar.topLeftView.setSingleClickListener { finish() }
        binding.bar.topTitle.text="我的好友"
        binding.llSearch.visibility= View.VISIBLE
        binding.run {
            tvBtnNext.setOnClickListener {
                if (TextUtils.isEmpty(binding.etSearch.text)){
                    showToast("请输入邀请码/手机号")
                }else{
                    keyword=""
                    pageNo = 1
                    getListData()
                }
            }
            etSearch.isFocusable = true
            etSearch.isFocusableInTouchMode = true
            etSearch.requestFocus()
            etSearch.setOnEditorActionListener { v, actionId, event ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = binding.etSearch.text.toString().trim()
                    if (!TextUtils.isEmpty(keyword)) {
                        binding.etSearch.clearFocus()
                        hideKeyboard(binding.etSearch)
                        pageNo = 1
                        getListData()
                    }else{
                        keyword=""
                        pageNo = 1
                        getListData()
                    }
                }
                false
            }
        }

        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        notDataView = NotDataView.notDataView(this, binding.rvList, binding.refreshLayout,"暂无数据")
        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (mAdapter.getItem(position).status!=1){
                showToast("你们还不是好友喔...")
                return@setOnItemClickListener
            }
            if (signIndex==1){
                if (TextUtils.isEmpty(url))
                    return@setOnItemClickListener
                val account = mAdapter.getItem(position).uid
                // 以单聊类型为例
                val sessionType = SessionTypeEnum.P2P
                val custBean = CusShareLiveAttachment()
                custBean.userId=anchorId
                custBean.nickName=userNick
                custBean.headImg=userAvatar

                custBean.title=liveTitle
                custBean.imgCover=coverUrl
                custBean.liveUrl=url
                custBean.liveId=liveID
                custBean.anchorId=anchorId
                //标签
                custBean.tags=""
                //添加代理
                custBean.agent= ""
                loge("xxxx==="+custBean.toString())
//                            // 创建一个自定义消息
                val custMsg = MessageBuilder.createCustomMessage(account,sessionType,custBean)
                // 发送给对方
                NIMClient.getService(MsgService::class.java).sendMessage(custMsg, true)
                    .setCallback(object : RequestCallback<Void> {
                        override fun onSuccess(result: Void?) {
                            showToast("分享成功...")
                            if (!LiveBlackList.isTaskShare && LiveBlackList.lastShareId!=mAdapter.getItem(position).uid){
                                LiveBlackList.lastShareId =mAdapter.getItem(position).uid
                                // 分享 任务
                                RxBus.getDefault()
                                    .post(RxBusBean(CustSignKey.LIVE_TASK, CustSignKey.LIVE_TASK, 3))
                            }
                            finish()
                        }

                        override fun onFailed(code: Int) {
                        }

                        override fun onException(exception: Throwable?) {
                        }

                    })

            }else{
                if (mShareBean==null)
                    return@setOnItemClickListener
                mShareBean?.let {
                    val materialChildList = mutableListOf<MaterialChildInfoBean>()
                    if (it.images.isNotEmpty()){
                        it.images.forEach {
                            materialChildList.add(MaterialChildInfoBean(0,it.url))
                        }
                    }
                    if (it.videos.isNotEmpty()){
                        it.videos.forEach {
                            materialChildList.add(MaterialChildInfoBean(1,it.url))
                        }
                    }


                    val account = mAdapter.getItem(position).uid
                    // 以单聊类型为例
                    val sessionType = SessionTypeEnum.P2P
                    val custBean = CusShareSourceAttachment()
                    custBean.contentX=it.content
                    custBean.crt_time=it.publish_time
                    custBean.headimg=it.headimg
                    custBean.id=it.id
                    custBean.images=if(materialChildList.size>0) Gson().toJson(materialChildList)   else ""
                    custBean.nickname=it.nickname
                    custBean.uid=it.uid
                    // 创建一个自定义消息
                    val custMsg = MessageBuilder.createCustomMessage(account,sessionType,custBean)
                    // 发送给对方
                    NIMClient.getService(MsgService::class.java).sendMessage(custMsg, true)
                        .setCallback(object : RequestCallback<Void> {
                            override fun onSuccess(result: Void?) {
                                showToast("分享成功...")
                                finish()
                            }

                            override fun onFailed(code: Int) {
                            }

                            override fun onException(exception: Throwable?) {
                            }

                        })

                }
            }


        }
        initRefreshLayout()
        pageNo = 1
        getListData()
        //链接融云
//        if (TextUtils.isEmpty(UserManager.getImToKen())){
//            if (!TextUtils.isEmpty(UserManager.getUserId())){
//                val map: HashMap<String, Any> = HashMap()
//                map["userid"] = UserManager.getUserId()
//                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGetRyToKenMethod( it1) }
//            }
//        }else{
//            connect(UserManager.getImToKen())
//        }
    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }

    override fun initData() {
        super.initData()
        binding.tvBtnNext.setOnClickListener {
            keyword = binding.etSearch.text.toString().trim()
            if (!TextUtils.isEmpty(keyword)) {
                binding.etSearch.clearFocus()
                hideKeyboard(binding.etSearch)
                pageNo = 1
                getListData()
            }
        }
    }


    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["keyword"] = keyword
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onFriendListMethod(it1) }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ShareFriendsListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(it)
            }
            againLoginMsg.observe(this@ShareFriendsListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onFriendListData.observe(this@ShareFriendsListActivity) {
                //我的好友列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData( it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        mAdapter.replaceData( it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            }

        }
    }
}